//
//  DBManager.m
//  OutesIOS
//
//  Created by norman on 2018/11/4.
//  Copyright © 2018 norman. All rights reserved.
//

#import <sqlite3.h>
#import "DBManager.h"

@interface DBManager () {
    sqlite3 *db;
    FMDatabase *fdb;
}


@end

@implementation DBManager


+(DBManager *)manager{
    static DBManager *db_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        db_manager = [[DBManager alloc] init];
    });
    return db_manager;
}

- (BOOL)open:(NSString*)database {
    NSString *nsPath = [[NSBundle mainBundle] pathForResource:database ofType:@"db"];
//    NSString *nsPath = [NSString stringWithFormat:@"%@/Documents/product/%@", NSHomeDirectory(), database];
    fdb = [FMDatabase databaseWithPath:nsPath];
    if (![fdb openWithFlags:SQLITE_OPEN_READONLY]) {
        NSLog(@"打开数据库失败");
        return NO;
    }
    return YES;
}

- (BOOL)addColumn:(NSString *)columnName withType:(NSString*)type inTable:(NSString*)tableName{
    if (fdb == nil) {
        return NO;
    }
    if ([fdb columnExists:columnName inTableWithName:tableName]) {
        return YES;
    }
    return [fdb executeUpdate:[NSString stringWithFormat:@"alter table '%@' add COLUMN '%@' %@ ", tableName, columnName, type]];
}

- (BOOL)update:sql withParameterDictionary:(NSDictionary *)arguments {
    if (fdb == nil) {
        return NO;
    }
    return [fdb executeUpdate:sql withParameterDictionary:arguments];
}

- (FMResultSet*)query:(NSString *)sql {
    if (fdb == nil) {
        return nil;
    }
    FMResultSet *s = [fdb executeQuery:sql];
    return s;
}

- (NSArray*)queryArrayData:(NSString *)sql {
    NSMutableArray *ret = [NSMutableArray new];
    if (fdb == nil) {
        return ret;
    }
    FMResultSet *s = [fdb executeQuery:sql];
    while ([s next]) {
        //retrieve values for each record
        [ret addObject:[s resultDictionary]];
    }
    return ret;
}

- (NSDictionary*)queryOneRowData:(NSString *)sql {
    NSDictionary *ret;
    if (fdb == nil) {
        return nil;
    }
    FMResultSet *s = [fdb executeQuery:sql];
    while ([s next]) {
        //retrieve values for each record
        ret = [s resultDictionary];
        break;
    }
    return ret;
}

- (NSString*)queryStringData:(NSString *)sql {
    if (fdb == nil) {
        return nil;
    }
    FMResultSet *s = [fdb executeQuery:sql];
    while ([s next]) {
        //retrieve values for each record
        return [s stringForColumnIndex:0];
    }
     return nil;
}

- (double)queryDoubleData:(NSString *)sql {
    if (fdb == nil) {
        return 0;
    }
    FMResultSet *s = [fdb executeQuery:sql];
    while ([s next]) {
        //retrieve values for each record
        return [s doubleForColumnIndex:0];
    }
    return 0;
}

- (void)close {
    if (fdb != nil) {
        [fdb close];
        fdb = nil;
    }
}

@end
